package com.mobile.chench.myvpnapplication;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Instrumentation;
import android.content.Intent;
import android.net.VpnService;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.mobile.chench.myvpnapplication.databinding.ActivityMainBinding;
import com.mobile.chench.testmoudle.TestScrollingActivity;

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        binding.sampleText.setText("这是一个VPN&抓包 Demo");



    }




    public void showToast(String content){
        Toast.makeText(this, content, Toast.LENGTH_SHORT).show();
    }




    @SuppressLint("NonConstantResourceId")
    public void onMainActyClick(View view) {

        switch (view.getId()){
            case R.id.start_vpn_service_btn:
                if (checkPermissionVpn()) {
                    Log.e("chenxh","VPNService 权限已获取,开启VPNService ");
                    openVpn();
                }else {
                    Log.e("chenxh","VPNService 权限未获取，即将发起请求...");
                    requestPermissionVpn();
                }
                break;
            case R.id.start_test_btn:
                startActivity(new Intent(MainActivity.this, TestScrollingActivity.class));
                break;
        }

    }


    private boolean checkPermissionVpn(){
        Intent prepare = VpnService.prepare(this);
        return null == prepare;
    }
    /**
     * VPN 初始化授权回调监听
     */
    // private  ActivityResultLauncher<Intent>   captureServiceLauncher=
    private ActivityResultLauncher<Intent> vpnServiceLauncher
            = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            if (result.getResultCode()==RESULT_OK) {
                openVpn();
                Log.e("chenxh","VPNService 已授权 开启VPNService");
            }else {
                Log.e("chenxh","VPNService 未授权 无法正常执行后续操作");
            }
        }});


    private void requestPermissionVpn(){
        Intent prepare = VpnService.prepare(this);
        vpnServiceLauncher.launch(prepare);
    }

    private void openVpn(){
        Intent startMyVpnService = new Intent(MainActivity.this,MyVPNService.class);
        startService(startMyVpnService);
    }


}